<?php

class AdminController extends Controller {

    private $_model;
    public $activeMenu = 'admin';

    /**
     * list all user here
     */
    public function actionIndex() {
        $model = new Admin('search');
        if (isset($_GET['Admin'])) {
            $model->attributes = $_GET['Admin'];
        }

        $this->render('index', compact('model'));
    }

    /**
     * add new member
     */
    public function actionCreate() {
        $model = new Admin('insert');
        $profile = new AdminProfile();

        //check password
        if (isset($_POST['Admin'])) {
            $model->attributes = $_POST['Admin'];
            $model->profile = $profile;
            $model->profile->attributes = $_POST['AdminProfile'];
            $model->profile->birthdate = date('Y-m-d', strtotime($model->profile->birthdate));
            $model->admin_nicename = $model->profile->firstname . ' ' . $model->profile->lastname;
            //check the upload file
            if (($fileUpload = CUploadedFile::getInstanceByName('avatar'))) {
                if (($uploadFileName = UploadHelper::saveAvatar($fileUpload))) {
                    $model->admin_avatar = $uploadFileName;
                }
            }

            if ($model->validate() && $model->profile->validate()) {
                $model->save();
                $model->profile->admin_id = $model->admin_id;
                $model->profile->save();
                Yii::app()->user->setFlash('success', 'Your profile has been updated');
            } else {
                Yii::app()->user->setFlash('error', 'Please check invalid fields');
            }

            $model->admin_password = $model->repassword = '';
        }

        $this->render('create', compact('model', 'profile'));
    }

    /**
     * update member
     */
    public function actionUpdate() {
        $model = $this->__loadModel();
        $profile = $model->profile;
        if ($profile == NULL) {
            $profile = new AdminProfile();
            $profile->admin_id = $model->admin_id;
        }

        //check password
        if (isset($_POST['Admin'])) {
            $model->attributes = $_POST['Admin'];
            $model->profile = $profile;
            $model->profile->attributes = $_POST['AdminProfile'];
            $model->profile->birthdate = date('Y-m-d', strtotime($model->profile->birthdate));
            $model->admin_nicename = $model->profile->firstname . ' ' . $model->profile->lastname;
            //check the upload file
            if (($fileUpload = CUploadedFile::getInstanceByName('avatar'))) {
                if (($uploadFileName = UploadHelper::saveAvatar($fileUpload))) {
                    $model->admin_avatar = $uploadFileName;
                }
            }

            $model->validate();
            $model->profile->validate();

            if ($model->save() && $model->profile->save()) {

                Yii::app()->user->setFlash('success', 'Your profile has been updated');
            } else {
                Yii::app()->user->setFlash('error', 'Please check invalid fields');
            }

            $model->admin_password = $model->repassword = '';
        }

        $profile->birthdate = date('d-m-Y', strtotime($profile->birthdate));
        $this->render('update', compact('model', 'profile'));
    }

    public function actionDelete($id) {
        // we only allow deletion via POST request
        $this->__loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $model = $this->__loadModel($id);
        $order = array();
        if ($model->admin_role == Admin::TECHNICIAN) {
            //set time default
            $now = time();
            //today
            $startOfToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            //weed
            $week_passed = (date('N') - 1) * 24 * 3600; // time since start of week in days
            $startOfWeek = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - $week_passed;
            //month
            $month_passed = (date('j') - 1) * 24 * 3600;
            $startOfMonth = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - $month_passed;

            //get data statistics total order
            $order['today'] = db()->createCommand()
                    ->select('COUNT(*)')
                    ->from('{{assign_report}}')
                    ->where('admin_id=:id AND status>:status AND create_time BETWEEN :start AND :end', array(
                        ':id' => $id,
                        ':status' => Assign::STATUS_ACCEPT,
                        ':start' => $startOfToday, ':end' => $now))
                    ->queryScalar();

            $order['week'] = db()->createCommand()
                    ->select('COUNT(*)')
                    ->from('{{assign_report}}')
                    ->where('user_id=:id AND status>:status AND create_time BETWEEN :start AND :end', array(
                        ':id' => $id,
                        ':status' => Assign::STATUS_ACCEPT,
                        ':start' => $startOfWeek, ':end' => $now))
                    ->queryScalar();

            $order['month'] = db()->createCommand()
                    ->select('COUNT(*)')
                    ->from('{{assign_report}}')
                    ->where('user_id=:id AND status>:status AND create_time BETWEEN :start AND :end', array(
                        ':id' => $id,
                        ':status' => Assign::STATUS_ACCEPT,
                        ':start' => $startOfMonth, ':end' => $now))
                    ->queryScalar();
            $order['total'] = db()->createCommand()
                    ->select('COUNT(*)')
                    ->from('{{assign_report}}')
                    ->where('user_id=:id AND status>:status', array(
                        ':id' => $id,
                        ':status' => Assign::STATUS_ACCEPT
                    ))
                    ->queryScalar();
        }

        $this->render('view', array(
            'model' => $model,
            'order' => $order
        ));
    }

    protected function __loadModel() {
        if ($this->_model === null) {
            if (isset($_GET['id'])) {
                $this->_model = Admin::model()->with('profile')->findByPk($_GET['id']);
            }
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_model;
    }

}